package com.example.demo2.controller;
import com.example.demo2.mapper.*;
import com.example.demo2.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpSession;


@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/setSession")
    public String setSession(HttpSession session) {
        session.setAttribute("uID",101);
        System.out.println("uID set to session: " + 101);
        return "";
    }

    @GetMapping("/findUserById")
    public User findUserById(HttpSession session) {
        Integer uID=(Integer) session.getAttribute("uID");
        if(uID!=null)
            return userMapper.findUserById(uID);
        else
        {
            System.out.println("uID is null");
            return new User(-1,null,null,null,null,null,null);
        }
    }

    @PutMapping("/updateAccount")
    public int updateAccount(User user,HttpSession session) {
        user.setUID((Integer)session.getAttribute("uID"));
        return userMapper.updateUser(user);
    }

    @PutMapping("/updateUserPw")
    public String updateUserPw(String oldUPw,String newUPw,HttpSession session) {
        Integer uID=(Integer)session.getAttribute("uID");
        if(userMapper.findPwdById(uID).equals(oldUPw))
        {
            if(userMapper.updateUserPw(uID,newUPw)==1)
            {
                return "success";
            }
            else
            {
                return "fail";
            }
        }
        else return("原密码错误")
        ;
    }

}
